// import router from '@/plugins/router'
import axios, {AxiosInstance, AxiosRequestConfig, InternalAxiosRequestConfig} from 'axios'
// @ts-ignore
import { ElLoading, ElMessage } from 'element-plus'
import useStorage from '@/composables/useStorage.ts'
import router from '@/router'
// interface IOptions {
//     loading?: boolean
//     message?: boolean
//     clearValidateError?: boolean
// }
const storage = useStorage()
export default class Axios {
    private instance: AxiosInstance
    private loading: any
    constructor(config: AxiosRequestConfig,   private isLoading=true) {
        this.instance = axios.create(config)
        this.interceptors()
    }

    public async request(config: AxiosRequestConfig) {
        return new Promise(async (resolve, reject) => {
            try {
                const response = await this.instance.request(config)
                resolve(response)
            } catch (error) {
                reject(error)
            }
        })
    }

    private interceptors() {
        this.interceptorsRequest()
        this.interceptorsResponse()
    }

    private interceptorsRequest() {
        this.instance.interceptors.request.use(
            (config: InternalAxiosRequestConfig) => {
                if (!this.loading && this.isLoading) {
                    this.loading = ElLoading.service({ background: 'rgba(255,255,255,0.1)', fullscreen: true })
                }
                config.headers['token'] = storage.get('token')
                return config
            },
            (error: any) => {
                return Promise.reject(error)
            },
        )
    }
    private interceptorsResponse() {
        this.instance.interceptors.response.use(
            (response) => {
                if (this.loading) {
                    this.loading.close()
                    this.loading = undefined
                }

                const res = response.data

                if (res.code !== 200) {
                    ElMessage.error(res.message)
                }
                return res
            },
            (error) => {
                if (this.loading) {
                    this.loading.close()
                    this.loading = undefined
                }
                // const res = error.response.data
                // if (res.statusCode == 401) {
                //     storage.remove('token')
                //     ElMessage.warning('登录已过期')
                //     router.push({
                //         name: 'login'
                //     })
                // }
                return Promise.reject(error)
            }
        )
    }
}
